<template>
  <div id="container">
    <div class="col1">
      <div v-for="item in list1" :id="item.nodeId" type="circle" name="cell" style="left:20px" class="startNode node">{{ item.name }}</div>
    </div>
     <div class="col2">
      <div v-for="item in list" :id="item.nodeId" type="square" name="cell" style="left:256px" class="nodeList node">{{ item.name }}</div>
    </div>
    <div class="col3">
      <div v-for="item in list2" :id="item.nodeId" type="circle" name="cell" style="right:20px" class="endNode node">{{ item.name }}</div>
    </div>
  </div>
</template>
<script>
 import  $ from "jquery"
 import axios from "axios"
 import 'jquery-ui/ui/widgets/draggable'
 import 'jquery-ui/ui/widgets/droppable'
 import 'jquery-ui/ui/widgets/resizable'
export default {
	data(){
		return {
			jsPlumb: null,
			list1:[{name:'开始',nodeId:'开始'}],
			list2:[{name:'结束',nodeId:'结束'}],
			list:JSON.parse(localStorage.getItem("list")),
			connlist:JSON.parse(localStorage.getItem("connlist"))
		}
	},
	created() {
		var _this = this;
           //这里可放到全局
	      window.getJson = function() {
	        return _this.getJson()
	   	 };
		this.jsPlumb = this.$jsPlumb.getInstance({
			Container:"container",   //选择器id
			EndpointStyle: { radius: 2, fill: "#acd"},  //端点样式
			PaintStyle: { stroke: '#fafafa',strokeWidth:4},// 绘画样式，默认8px线宽  #456
			HoverPaintStyle: { stroke: '#1E90FF'}, // 默认悬停样式  默认为null
			EndpointHoverStyle: { fill: '#acd', radius:4 }, // 端点悬停样式
			ConnectionOverlays:[                 
				["Arrow",{
					location:1,
					paintStyle: {
						stroke: '#00688B',
						fill: '#00688B',
					}
				}]
			],
			Connector:["Straight",{gap:1}],     //要使用的默认连接器的类型：折线，流程等
			DrapOptions:{cursor:"crosshair",zIndex:2000}
		});
	},
	mounted() {
		let ins = this.jsPlumb,
			allConnection = ins.getAllConnections();
		ins.batch(() => {
			this.initAll();
			this.connectionAll();
			this.deleteConnection();
		});
		this.switchContainer(true,true,false);
	},
	methods:{
	     getJson () {
	         var connects = [];
	         $.each(this.jsPlumb.getAllConnections(), function (idx, connection) {
		        connects.push({
		            pageSourceId: connection.sourceId,
		            pageTargetId: connection.targetId
		        });
		    });
	         var blocks = [];
		    $("#container .node").each(function (idx, elem) {
		           var $elem = $(elem);
	                blocks.push({
	                    blockName: $elem.text(),
	                    type: $elem.attr('type'),
	                    blockX: parseInt($elem.css("left")),
	                    blockY: parseInt($elem.css("top")),
	                    dataId: $elem.attr('id'),
	                });
		    });
		    var jsonData={};
		    jsonData.blocks=blocks;
		    jsonData.connects=connects;
		    jsonData=JSON.stringify(jsonData)
		    localStorage.setItem("flowJson", jsonData)
	     },
		initAll () {
			let rl = this.list1;
			for (let i = 0; i < rl.length; i++) {
				this.init(rl[i].nodeId)
			}
			let rl2 = this.list2;
			for (let i = 0; i < rl2.length; i++) {
				this.init(rl2[i].nodeId)
			}
			let rl3 = this.list;
			for (let i = 0; i < rl3.length; i++) {
				this.init(rl3[i].nodeId)
				if(i===0){
					$("#"+rl3[i].nodeId).css("top",40)
				}else if(i===(rl3.length-1)){
					$("#"+rl3[i].nodeId).css("top",420)
				}else{
					var total=480-rl3.length*40
				     var space=total/(rl3.length-1)
					$("#"+rl3[i].nodeId).css("top",(space+40)*i)
				}
				
			}
		},
		// 初始化规则使其可以连线、拖拽
		init (id) {
			let ins = this.jsPlumb,
			elem = document.getElementById(id);
		     ins.addEndpoint(id, { anchors: "Right" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
		      ins.addEndpoint(id, { anchors: "Left" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
		       ins.addEndpoint(id, { anchors: "Bottom" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
		        ins.addEndpoint(id, { anchors: "Top" }, {
			       isSource: true,    //是否可以拖动（作为连线起点）
			       connector: ["Flowchart", { stub: [10,20], gap: 2, cornerRadius:10, alwaysRespectStubs: true }],  //连接线的样式种类有[Bezier],[Flowchart],[StateMachine ],[Straight ]
			        isTarget: true,    //是否可以放置（连线终点）
			        maxConnections: -1,    // 设置连接点最多可以连接几条线
		     });
			ins.makeSource(elem,{
				anchor: ["Continuous", {anchorCount:200, shape:"Rectangle"}],
				allowLoopback: false
			});
			ins.makeTarget(elem,{
				anchor: ["Continuous", {anchorCount:200, shape:"Rectangle"}],
				allowLoopback: false
			}); 
			// ins.draggable(elem,{
			// 	containment:  "this"
			// });  
			  $("#" + id).draggable({
		          containment: "this"});
		},
		connectionAll () {
			let ins = this.jsPlumb;
			ins.ready(() => {
				for (let i = 0; i < this.connlist.length; i++) {
					let conn = this.connlist[i],
							connection = ins.connect({
								source:conn.sourceNodeId,
								target:conn.targetNodeId
							});
					connection.setPaintStyle({stroke:"#fafafa",strokeWidth:4})
				}
			})
		},
		deleteConnection(){
			   let self=this
			   let ins = self.jsPlumb
			    ins.bind("dblclick", function (conn, originalEvent) {
			        self.$confirm({
			        title: '确定删除此连线吗?',
			        onOk () {
			            ins.deleteConnection(conn);
			        }
			      })
			    });
		},
		switchContainer (target,source,draggable) {
			let elem = document.getElementsByName("cell"),
				  ins = this.jsPlumb;
			ins.setSourceEnabled(elem,source);
			ins.setTargetEnabled(elem,target);
			ins.setDraggable(elem,draggable);
		},
	}
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

  #container {
    position: relative;
    background: #efefef;
    width: 100%;
    height: 500px;
  }

  .col2, .col1 {
    float: left;
  }

  .col1 {
    margin-left: 40px;
  }

  .col2 {
    margin-left: 150px;
  }
  .col3 {
    margin-left: 260px;
  }
  .nodeList {
    width: 100px;
    height: 40px;
    line-height: 40px;
    background: lightcyan;
    text-align: center;
    position: absolute;
    border-radius: 10px;
  }
  .startNode,.endNode{
  	width: 60px;
     height: 60px;
     line-height: 60px;
     border-radius: 50%;
     text-align: center;
     background: lightcyan;
     top: 30px;
     position: absolute;
  }
</style>
